<template>
    <div style="font-size:15px;font-weight: 600;margin-left: 60px;">{{ !dataForm.id ? $t('add') : '编辑' }}产品
    </div>
     <div class="reject" v-if="dataForm.id && dataForm.audit === 2">
        <span>驳回原因：
            <a  style="color: red;font-weight: 400;">{{dataForm.auditRemark}}</a>
        </span>
    </div>
    <div>
        <el-tabs v-model="activeTab" style="margin-left: 60px;margin-top: 20px;">
            <el-tab-pane label="基础信息" name="tab1">
                <el-form label-width="110px" style="margin-top: 20px;margin-left: -32px;" :model="dataForm"
                    :rules="rules" ref="dataFormRef">
                    <el-row>
                        <el-col>
                            <el-form-item label="系列名称" prop="seriesName">
                                <el-input style="width: 500px;" v-model="dataForm.seriesName" placeholder="请输入系列名称">
                                    <template #append>系列</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="产品分类" prop="class3Id">
                                <el-cascader :options="classOptions" clearable :props="cascaderProps" filterable
                                    style="width: 500px;" v-model="selectedClassPath" @change="handleClassChange"
                                    placeholder="请选择分类"></el-cascader>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="产品品牌" prop="brandName">
                                <el-select v-model="dataForm.brandName" placeholder="请选择品牌" filterable @change="handleBrandChange"
                                    style="width: 500px;" remote reserve-keyword :remote-method="getBrandList" remote-show-suffix :loading="loading">
                                    <el-option v-for="item in brandOptions" :key="item.id" :label="item.brandName"
                                        :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="产品主图" prop="mainImages">
                                <el-upload :action="uploadUrl" :file-list="mainImgList" :before-upload="beforeUpload"
                                    :on-success="successHandle" :show-file-list="false" class="brand-upload" :auto-upload="true">
                                    <div class="upload-box">
                                        <img v-if="!dataForm.mainImages" src="../../assets/images/upload.png" alt=""
                                            class="icon" />
                                        <img v-else :src="dataForm.mainImages" alt="上传的图片" class="uploaded-image" />
                                    </div>
                                    <template v-slot:tip>
                                        <div class="el-upload__tip">
                                            {{ t("upload.tip", { format: "jpg、png" }) || '只能上传jpg/png文件' }}
                                        </div>
                                    </template>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="产品详情" prop="imgUrls">
                                <div class="image-upload-container">
                                    <div class="upload-tip">
                                        <div class="tip-text">仅支持上传图片，最多可上传10张，已上传 {{ uploadedFiles.length }}/10
                                        </div>
                                    </div>
                                    <el-upload class="upload-dragger" :action="uploadUrl" :limit="10"
                                        :on-success="handleUploadSuccess" :before-upload="beforeUpload"
                                        :file-list="uploadedFiles" list-type="picture-card" :show-file-list="true"
                                        :auto-upload="true" :class="{ 'hide': uploadedFiles.length >= 10 }"
                                        :on-preview="handlePictureCardPreview"
                                        :on-remove="handleRemove"
                                               multiple
                                    >
                                        <div class="upload-tip">
                                            <el-icon>
                                                <Plus />
                                            </el-icon>
                                        </div>
                                    </el-upload>
                                    <el-dialog v-model="dialogVisible">
                                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                                    </el-dialog>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item>
                                <el-button type="primary" @click="showPreview = true">页面预览</el-button>
                                <el-image-viewer v-if="showPreview" :url-list="srcList" show-progress :initial-index="4"
                                    @close="showPreview = false" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="型号信息" name="tab2">
                <el-form style="margin-top: 20px;">
                    <div class="model">
                        <el-form-item>
                            <el-button type="primary" @click="addTab" class="add-button">添加型号</el-button>
                        </el-form-item>
                        <div v-if="showBackgroundImage" style="text-align: center;">
                            <img src="../../assets/images/nocproduvt-add.png" alt="">
                        </div>
                        <el-tabs v-model="editableTabsValue" type="card" class="demo-tabs" closable
                            @tab-remove="removeTab">
                            <el-tab-pane v-for="(item, index) in editableTabs" :key="item.name"
                                :label="item.productName || '未命名型号'" :name="item.name">
                                <!-- 型号名称输入 -->
                                <el-form-item label="型号名称" prop="name" label-width="">
                                    <el-input placeholder="请输入型号名称" v-model="item.productName"
                                        @blur="checkProductNameDuplicate(item)"></el-input>
                                </el-form-item>

                                <!-- 图片/视频上传区域（每个tab独立文件列表） -->
                                <div style="color: rgba(56, 56, 56, 1);margin-bottom: 15px;font-size: 13px;">产品图片/视频
                                </div>
                                <el-form-item prop="name">
                                    <div class="image-upload-container" style="width: 684px;">
                                        <div class="upload-tip">
                                            <div style=" color:rgba(56, 56, 56, 1);">产品图片/视频上传</div>
                                            仅支持上传图片、视频，最多可上传6张与1个视频，
                                            已上传 {{ item.imageFiles?.length }}/6图片、{{ item.videoFiles?.length
                                            }}/1视频
                                        </div>

                                        <!-- 图片上传组件（绑定当前tab的imageFiles） -->
                                        <div class="image-upload-section">
                                            <div class="image-upload-label">图片：</div>
                                            <el-upload class="upload-dragger" :action="uploadUrl" :limit="6"
                                                :before-upload="beforeImageUpload" :file-list="item.imageFiles"
                                                :class="{ 'hide': item.imageFiles.length >= 6 }"
                                                :on-success="(res: any, file: any, fileList: any) => handleImageSuccess(res, fileList, item)"
                                                list-type="picture-card" :show-file-list="true" :auto-upload="true"
                                                :on-preview="handlePictureCardPreview"
                                                :on-remove="(file:any, fileList:any) => handleRemove2(file, fileList, item)">
                                                <el-icon>
                                                    <Plus />
                                                </el-icon>
                                            </el-upload>
                                            <el-dialog v-model="dialogVisible">
                                                <img w-full :src="dialogImageUrl" alt="Preview Image" />
                                            </el-dialog>
                                        </div>

                                        <!-- 视频上传组件（绑定当前tab的videoFiles） -->
                                        <div class="video-upload-section">
                                            <div class="video-upload-label">视频：</div>
                                            <el-upload class="upload-dragger" style="width: 200px;"
                                                :action="uploadUrl"
                                                :limit="1"
                                                :class="{ 'hide': item.videoFiles.length >= 1 }"
                                                :on-success="(res: any, file: any, fileList: any) => handleVideoSuccess(res, fileList, item)"
                                                :before-upload="beforeVideoUpload"
                                                :file-list="item.videoFiles"
                                                list-type="picture-card"
                                                :show-file-list="true"
                                                :auto-upload="true"
                                                :on-preview="handleVideoPreview"
                                                :on-remove="(file:any, fileList:any) => handleRemove3(file, fileList, item)"
                                                accept="video/*">  <!-- 添加accept属性限制文件类型 -->
                                                <div>
                                                    <el-icon>
                                                        <VideoCamera />
                                                    </el-icon>
                                                </div>
                                                <template #file="{ file }">  <!-- 添加文件显示模板 -->
                                                    <div class="video-preview-container" style="display: flex;">
                                                        <video controls width="100%" style="width: 130px;height: 130px;">
                                                            <source :src="file.url" type="video/mp4">
                                                            您的浏览器不支持视频播放
                                                        </video>
                                                        <span class="video-actions">
                                                            <span class="video-delete" @click.stop="handleRemove4(file, item.videoFiles, item)">
                                                                <el-icon><Delete /></el-icon>
                                                            </span>
                                                        </span>
                                                    </div>
                                                </template>
                                            </el-upload>
                                        </div>
                                                            </div>
                                </el-form-item>
                                <el-form-item label="参数信息" prop="name" style="font-weight: 600;"></el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="addOrUpdateHandle()"
                                        class="add-button">添加属性组</el-button>
                                    <el-button type="primary" @click="syncAttributeGroups(item, index)"
                                        :disabled="isSyncButtonDisabled(item, index)"
                                        class="add-button">同步属性组</el-button>
                                </el-form-item>

                                <!-- 属性组示例（假设每个tab有独立的属性组数据） -->
                                <div v-for="(group, groupIndex) in item.productAttrGroupList" :key="groupIndex"
                                    style="display: flex; align-items: center;">
                                    <div class="attribute-group">
                                        <div style="font-size: 14px; font-weight: 600;margin-bottom: 30px;">{{
                                            group.groupName }}
                                        </div>
                                        <el-form-item v-for="(itemInput, inputIndex) in group.productAttrs"
                                            :key="inputIndex" style="margin-bottom: 20px;">
                                            <div style="width: 96px;">{{ itemInput.attrName }}</div>
                                            <el-input type="text" clearable placeholder="请输入"
                                                class="attribute-group-input" v-model="itemInput.attrValue"></el-input>
                                        </el-form-item>
                                    </div>
                                    <div style="margin-left: 20px;">
                                        <img src="../../assets/images/delete2.jpg" alt=""
                                            @click="deleteAttributeGroup(item, groupIndex)">
                                    </div>
                                </div>
                            </el-tab-pane>
                        </el-tabs>
                    </div>
                </el-form>
            </el-tab-pane>
        </el-tabs>
    </div>
    <div class="foot">
        <el-button class="quxiao" @click="cancel()">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update :key="addKey" ref="addOrUpdateRef" @refreshDataList="refreshDataList"></add-or-update>
</template>

<script lang="ts" setup>
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from 'vue-router';
import useView from "@/hooks/useView";
import { nextTick, onMounted, reactive, ref, toRefs, computed } from "vue";
import AddOrUpdate from "./attribute-list-group.vue";
import { useI18n } from "vue-i18n";
import type { TabPaneName } from 'element-plus';
import { IObject } from "@/types/interface";
import app from "@/constants/app";
import { getToken } from "@/utils/cache";
import type { UploadProps, UploadUserFile } from 'element-plus'
import item from "element-plus/es/components/space/src/item";

const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const dataForm = reactive({
    id: "",
    seriesName: "",
    class1Id: "",
    class2Id: "",
    class3Id: "",
    className: "",
    brandId: "",
    brandName: "",
    mainImages: "",
    imgUrls: "", // 改为字符串类型，存储逗号分隔的URL
    productList: [] as Product[],
    audit:"",
    auditRemark:""
});

const handleRemove4 = (file: any, fileList: any, item: Product) => {
    // 从 fileList 中移除当前文件
    const index = fileList.findIndex((f: any) => f.uid === file.uid);
    if (index !== -1) {
        fileList.splice(index, 1);
    }

    // 更新 item.videoFiles 为空数组
    item.videoFiles = [];
    item.productVideoUrl = "";
};

//点击图片放大按钮查看
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

const view = reactive({});

const state = reactive({ ...useView(view), ...toRefs(view) });
const router = useRouter();
const route = useRoute();
const id = route.query.id;
// 修改 props 为 cascaderProps
const cascaderProps = reactive({ value: "id", label: "className", children: "children", emitPath: true });

// const uploadUrl = 'http://localhost:8086/sys/oss/upload';
const uploadUrl = `${app.api}/sys/oss/upload`;
const mainImgList = ref<IObject[]>([]);

// 分类选项
const classOptions = ref<any[]>([]);
// 品牌选项
const brandOptions = ref<any[]>([]);
// 选中的分类路径
const selectedClassPath = ref<string[]>([]);

// tab切换显示
const activeTab = ref('tab1');

//正则校验
const rules = ref({
    seriesName: [
        { required: true, message: t("validate.required"), trigger: "blur" },
        {
            validator: (rule: any, value: any, callback: any) => {
                if (value && value.includes('系列')) {
                    callback(new Error('系列名称不能包含"系列"字样'));
                } else {
                    callback();
                }
            }, trigger: 'blur'
        }
    ],
    brandId: [{ required: true, message: t("validate.required"), trigger: "change" }],
    class3Id: [{ required: true, message: t("validate.required"), trigger: "change" }],
    mainImages: [{ required: true, message: t("validate.required"), trigger: "change" }],
    imgUrls: [{ required: true, message: t("validate.required"), trigger: "change" }],
    brandName: [{ required: true, message: t("validate.required"), trigger: "change" }],
});


const init = () => {
    // 重置表单数据
    if (dataFormRef.value) {
        dataFormRef.value.resetFields();
    }

    if (id) {
        dataForm.id = id.toString();
        showBackgroundImage.value = false;
        baseService.get("/noc/productseries/info/" + id).then((res) => {
            if (res.code === 0 && res.data) {
                Object.assign(dataForm, res.data);
                console.log(dataForm);
                if (res.data.mainImages) {
                    mainImgList.value = [{
                        name: 'mainImage',
                        url: res.data.mainImages,
                        response: { url: res.data.mainImages },
                        status: 'success'
                    }];
                }
                // 如果有已上传的图片，初始化uploadedFiles
                if (dataForm.imgUrls) {
                    const urls = dataForm.imgUrls.split(',');
                    uploadedFiles.value = urls.map((url, index) => ({
                        name: `已上传图片${index + 1}`,
                        url: url,
                        response: { url: url },
                        status: 'success'
                    }));
                }

                // 回显分类路径
                if (dataForm.class1Id && dataForm.class2Id && dataForm.class3Id) {
                    selectedClassPath.value = [dataForm.class1Id, dataForm.class2Id, dataForm.class3Id];
                } else if (dataForm.class1Id && dataForm.class2Id) {
                    selectedClassPath.value = [dataForm.class1Id, dataForm.class2Id];
                } else if (dataForm.class1Id) {
                    selectedClassPath.value = [dataForm.class1Id];
                }

                // 确保 productAttrGroupList 是一个数组
                const productList = Array.isArray(res.data.productList) ? res.data.productList : [];
                console.log(productList);
                editableTabs.value = productList.map((product: any) => {
                    console.log(product);
                    // 确保 banarImg 是字符串，否则设为空数组
                    let imageFiles: { name: string; url: any; response: { url: any; }; status: string; }[] = [];
                    if (product.banarImg) {
                        const banarImg = product.banarImg.split(',');
                        imageFiles = banarImg.map((url: string, index: number) => ({
                            name: `已上传图片${index + 1}`,
                            url: url,
                            response: { url: url },
                            status: 'success'
                        }));
                    }
                    let videoFiles: { name: string; url: any; response: { url: any; }; status: string; }[] = [];
                    if (product.productVideoUrl) {
                        videoFiles = [{
                            name: `已上传视频`,
                            url: product.productVideoUrl,
                            response: { url: product.productVideoUrl },
                            status: 'success'
                        }];
                    }
                    // 确保 productAttrGroupList 是一个数组
                    const attrGroupList = Array.isArray(product.productAttrGroupList) ? product.productAttrGroupList : [];
                    return {
                        id: product.id,
                        seriesId: product.seriesId,
                        productName: product.productName,
                        name: product.productName,
                        banarImg: product.banarImg,
                        productVideoUrl: product.productVideoUrl,
                        imageFiles: imageFiles,
                        videoFiles: videoFiles,
                        productAttrGroupList: attrGroupList.map((productAttrGroup: any) => {
                            // 确保 productAttrs 是一个数组
                            const attrs = Array.isArray(productAttrGroup.productAttrs) ? productAttrGroup.productAttrs : [];
                            return {
                                id: productAttrGroup.id,
                                productId: productAttrGroup.productId,
                                groupId: productAttrGroup.groupId,
                                seriesId: productAttrGroup.seriesId,
                                groupName: productAttrGroup.groupName,
                                productAttrs: attrs.map((productAttr: any) => ({
                                    id: productAttr.id,
                                    productId: productAttr.productId,
                                    attrId: productAttr.attrId,
                                    productAttrGroupId: productAttr.productAttrGroupId,
                                    attrName: productAttr.attrName,
                                    attrValue: productAttr.attrValue
                                }))
                            };
                        })
                    };
                });
                // 如果存在型号数据，默认选中第一个
                console.log(editableTabs.value);
                if (editableTabs.value && editableTabs.value.length > 0) {
                    editableTabsValue.value = editableTabs.value[0]?.name ?? '';
                }
            } else {
                ElMessage.error('获取产品系列信息失败');
            }
        });
    }
};

// 可编辑标签页数据结构（每个tab独立存储图片/视频列表和属性组）
interface TabItem {
    title: string;
    name: string;
    imageFiles: File[];
    videoFiles: File[];
    attributeGroups: {
        title: string;
        items: { label: string; value: string }[]
    }[];
}

interface Product {
    id?: number;
    seriesId?: number;
    name?: string;
    productName: string;
    banarImg: string;
    productVideoUrl: string;
    imageFiles?: File[];
    videoFiles?: File[];
    productAttrGroupList: {
        id?: number;
        productId?: number;
        groupId: number;
        seriesId?: number;
        groupName: string;
        productAttrs: {
            id: number;
            productId: number;
            attrId: number;
            productAttrGroupId: number;
            attrName: string;
            attrValue: string
        }[]
    }[];
}

//点击图片删除
const handleRemove = async (file: any, fileList: any[]) => {
    uploadedFiles.value = fileList;
    const urls = fileList.map(item => item.response?.url).filter(url => url);
    dataForm.imgUrls = urls.join(',');
     // 可选：显示删除成功消息
    ElMessage.success('图片已删除');
};

const handleRemove2 = (file: any, fileList: any[], currentItem: Product) => {
    currentItem.imageFiles = fileList;
    const urls = fileList.map(item => item.response?.url).filter(url => url);
    currentItem.banarImg = urls.join(',');
    // 可选：显示删除成功消息
    ElMessage.success('图片已删除');
};

const handleRemove3 = (file: any, fileList: any[], currentItem: Product) => {
    currentItem.videoFiles = fileList;
    const urls = fileList.map(item => item.response?.url).filter(url => url);
    currentItem.productVideoUrl = urls.join(',');
  // 可选：显示删除成功消息
    ElMessage.success('视频已删除');
};

const editableTabs = ref<Product[]>([]); // 响应式tab列表
const editableTabsValue = ref<string>(''); // 当前激活的tab名称
let tabIndex = 0; // 用于生成唯一标识

//校验同一个产品的型号名称不能相同
const checkProductNameDuplicate = (currentItem: Product) => {
    const productNames = editableTabs.value.map(item => item.productName);
    const currentIndex = editableTabs.value.findIndex(item => item === currentItem);
    const currentName = currentItem.productName;
    const filteredNames = productNames.filter((name, index) => index !== currentIndex && name === currentName);
    if (filteredNames.length > 0) {
        ElMessage.error('同一个产品的型号名称不能相同');
        // 可以选择重置当前输入框的值，这里假设你想这么做，可根据实际需求调整
        currentItem.productName = '';
    }
};


// 控制背景图片显示的状态变量
const showBackgroundImage = ref(true);

// 添加新tab（初始化独立的文件列表和属性组）
const addTab = () => {
    const newTabName = `tab-${++tabIndex}`;
    editableTabs.value.push({
        productName: '', // 默认标题
        name: newTabName,
        banarImg: "",
        productVideoUrl: "",
        imageFiles: [] as any[], // 独立图片列表
        videoFiles: [] as any[], // 独立视频列表
        productAttrGroupList: [] as any[], // 独立属性组数据
    });
    editableTabsValue.value = newTabName; // 自动切换到新tab

    //点击隐藏图片
    showBackgroundImage.value = false;


};

// 删除tab
const removeTab = (targetName: string) => {
    const index = editableTabs.value.findIndex(item => item.name === targetName);
    const item = editableTabs.value[index];
    if (item.id) {
        baseService.get("/noc/productuserquotation/existQuotation/" + item.id).then((res) => {
            if (res.code === 0) {
                if (res.data) {
                    ElMessage.error('当前产品型号有供应商报价，无法删除！！');
                } else {
                    if (index > -1) {
                        editableTabs.value.splice(index, 1);
                        // 删除后切换到前一个tab
                        if (editableTabsValue.value === targetName) {
                            index > 0 ?
                                editableTabsValue.value = editableTabs.value[index - 1]?.name || '' :
                                editableTabsValue.value = editableTabs.value[index]?.name || '';
                        }
                    }
                }
            } else {
                ElMessage.error('删除型号请求失败');
            }
        })
    } else {
        if (index > -1) {
            editableTabs.value.splice(index, 1);
            // 删除后切换到前一个tab
            if (editableTabsValue.value === targetName) {
                index > 0 ?
                    editableTabsValue.value = editableTabs.value[index - 1]?.name || '' :
                    editableTabsValue.value = editableTabs.value[index]?.name || '';
            }
        }
    }

};


// 上传前校验（通用图片校验）
const beforeImageUpload = (file: File) => {
    const isImage = /^image\//.test(file.type);
    const isLimit = file.size / 1024 / 1024 < 5; // 5MB限制
    if (!isImage) {
        ElMessage.error('仅支持图片格式');
        return false;
    }
    if (!isLimit) {
        ElMessage.error('图片大小不能超过5MB');
        return false;
    }
    return true;
};

// 视频上传前校验
const beforeVideoUpload = (file: File) => {
    const isVideo = /^video\//.test(file.type);
    const isLimit = file.size / 1024 / 1024 < 50; // 50MB限制
    if (!isVideo) {
        ElMessage.error('仅支持视频格式');
        return false;
    }
    if (!isLimit) {
        ElMessage.error('视频大小不能超过50MB');
        return false;
    }
    return true;
};


// 删除属性组（示例）
const deleteAttributeGroup = (item: Product, index: number) => {
    item.productAttrGroupList.splice(index, 1);
};


// 图片输入框引用，指定类型并初始化为null
const imageInput = ref<HTMLInputElement | null>(null);

onMounted(() => {
    const inputElement = document.querySelector('input[type="file"]');
    if (inputElement) {
        try {
            imageInput.value = inputElement as HTMLInputElement;
        } catch (error) {
            console.error("获取input元素时出错:", error);
        }
    }
});

// 打开图片上传对话框
const openImageUpload = () => {
    if (imageInput.value) {
        imageInput.value.click();
    }
};

// 通用的图片格式及大小验证函数（可复用）
const validateImage = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    const isLimit = file.size / 1024 / 1024 < 5; // 限制 5MB 以内，可调整
    if (!isJPG && !isPNG) {
        ElMessage.error('仅支持 JPG/PNG 格式的图片');
        return false;
    }
    if (!isLimit) {
        ElMessage.error('图片大小不能超过 5MB');
        return false;
    }
    return true;
};

// 产品详情图片上传前验证（beforeUpload函数修改）
const beforeUpload = (file: any) => {
  //验证单个文件夹是否要求
  const isImage = /image\//.test(file.type);
  const isLimit = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error('仅支持图片格式');
    return false;
  }
  if (!isLimit) {
    ElMessage.error('图片大小不能超过 5MB');
    return false;
  }
  return true;
};
//   //如果已经有文件，移除旧文件
//   if (mainImgList.value.length > 0) {
//     mainImgList.value = [];
//   }
//   //清除文件列表后，手动将新文件添加到文件列表中
//   mainImgList.value.push(file);
//   return validateImage(file);
// };

const successHandle = (res: IObject, file: IObject) => {
  if (res.code !== 0) {
    return ElMessage.error(res.msg);
  }
  // 设置图片URL
  dataForm.mainImages = res.url;

  // 更新文件列表，确保UI能够正确显示上传的图片
  mainImgList.value = [{
    name: file.name,
    url: res.url,
    response: { url: res.url },
    status: 'success'
  }];

  ElMessage.success({
    message: t("prompt.success") || '上传成功',
    duration: 500
  });
 dataFormRef.value.validateField('mainImages');
};

const uploadedFiles = ref<File[]>([]);

// 处理产品详情图片上传成功
const handleUploadSuccess = (res: any, file: any, fileList: any[]) => {
    if (res.code !== 0) {
        ElMessage.error(res.msg || '上传失败');
        return;
    }

    // 更新上传文件列表
    uploadedFiles.value = fileList;

    // 收集所有已上传图片的URL
    const urls = fileList.map(item => item.response?.url).filter(url => url);

    // 将所有URL以逗号分隔存储到dataForm.imgUrls
    dataForm.imgUrls = urls.join(',');

    ElMessage.success({
        message: '上传成功',
        duration: 500
    });
    dataFormRef.value.validateField('imgUrls');
};

const handleImageSuccess = (res: any, fileList: any[], item: Product) => {
    if (res.code !== 0) {
        ElMessage.error(res.msg || '上传失败');
        return;
    }
    //   const index = editableTabs.value.findIndex(item => item.name === editableTabsValue.value);
    //   const item = editableTabs.value[index];
    // 更新上传文件列表
    item.imageFiles = fileList;

    // 收集所有已上传图片的URL
    const urls = fileList.map(item => item.response?.url).filter(url => url);

    // 将所有URL以逗号分隔存储到dataForm.imgUrls
    item.banarImg = urls.join(',');

    ElMessage.success({
        message: '上传成功',
        duration: 500
    });
};


const handleVideoSuccess = (res: any, fileList: any[], item: Product) => {
    if (res.code !== 0) {
        ElMessage.error(res.msg || '上传失败');
        return;
    }
    //   const index = editableTabs.value.findIndex(item => item.name === editableTabsValue.value);
    //   const item = editableTabs.value[index];
    // 更新上传文件列表
    item.videoFiles = fileList;
    // 将所有URL以逗号分隔存储到dataForm.imgUrls
    item.productVideoUrl = res.url;

    ElMessage.success({
        message: '上传成功',
        duration: 500
    });
};
// 保留handleChange函数用于其他地方可能的引用
const handleChange = (file: File, fileList: File[]) => {
    uploadedFiles.value = fileList;
};

const handleBrandChange = (value: string) => {
    dataForm.brandId = value;
};

// 图片上传接口地址，需替换为实际地址
// const imageUploadUrl = 'https://your-image-upload-server-url.com/upload';
// 视频上传接口地址，需替换为实际地址
// const videoUploadUrl = 'https://your-video-upload-server-url.com/upload';

const showPreview = ref(false);

// 页面预览
const srcList = computed(() => {
    // 如果有上传的图片，则使用上传的图片URL进行预览
    if (dataForm.imgUrls && dataForm.imgUrls.length > 0) {
        return dataForm.imgUrls.split(',');
    }
    // 否则返回默认图片列表
    return [
        'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
        'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg',
        'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
        'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg',
        'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',
        'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',
        'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg'
    ];
});

const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }

    // 检查是否有型号数据
    if (editableTabs.value.length > 0) {
      // 验证每个型号
      for (const [index, product] of editableTabs.value.entries()) {
        // 检查型号名称
        if (!product.productName) {
          ElMessage.error(`型号名称不能为空`);
          return false;
        }

        // 检查图片或视频
        if ((product.imageFiles?.length || 0) === 0 && (product.videoFiles?.length || 0) === 0) {
          ElMessage.error(`型号 "${product.productName}" 必须上传至少一张图片或一个视频`);
          return false;
        }
      }

      // 验证型号名称是否唯一
      const allProductNames = editableTabs.value.map(item => item.productName);
      const uniqueNames = [...new Set(allProductNames)];
      if (uniqueNames.length !== allProductNames.length) {
        ElMessage.error('同一个产品的型号名称不能相同');
        return false;
      }
    }

    // 处理提交数据
    dataForm.productList = editableTabs.value.map(product => {
      return {
        id: product.id,
        seriesId: product.seriesId,
        productName: product.productName,
        banarImg: product.banarImg,
        productVideoUrl: product.productVideoUrl,
        productAttrGroupList: product.productAttrGroupList.map(group => {
          return {
            id: group.id,
            productId: group.productId,
            groupId: group.groupId,
            seriesId: group.seriesId,
            groupName: group.groupName,
            productAttrs: group.productAttrs.map(attr => {
              return {
                id: attr.id,
                productId: attr.id,
                attrId: attr.attrId,
                productAttrGroupId: attr.id,
                attrName: attr.attrName,
                attrValue: attr.attrValue,
              };
            })
          };
        })
      }
    });

    const url = !dataForm.id ? "/noc/productseries/save" : "/noc/productseries/update";
    baseService[!dataForm.id ? 'post' : 'put'](url, dataForm).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          const from = Array.isArray(route.query.from)
            ? route.query.from[0]
            : route.query.from
          // 关闭当前标签页（需确保useView hook已正确配置）
          state.closeCurrentTab();
           router.push(from as string) 
        //   router.push(from as string).then(() => {
        //     router.go(0); // 导航完成后刷新页面
        //   });
        }
      });
    });
  });
};
// 新增
const addKey = ref(0);
const addOrUpdateRef = ref();
const addOrUpdateHandle = (id?: number) => {
    addKey.value++;
    nextTick(() => {
        addOrUpdateRef.value.init(id);
    });
};

// 接收属性组数据并添加到当前选中的型号中
const refreshDataList = (attrGroupData: any) => {
    if (!attrGroupData || !editableTabsValue.value) {
        return;
    }

    // 查找当前选中的型号
    const currentTabIndex = editableTabs.value.findIndex(item => item.name === editableTabsValue.value);

    // 获取当前选中的型号
    const currentTab = editableTabs.value[currentTabIndex];

    // 如果productAttrGroupList不存在，则初始化为空数组
    if (!currentTab.productAttrGroupList) {
        currentTab.productAttrGroupList = [];
    }

    // 获取当前型号已有的属性组ID列表
    const existingGroupIds = currentTab.productAttrGroupList.map(group => group.groupId);


    // 将新的属性组数据添加到当前型号的productAttrGroupList中
    if (Array.isArray(attrGroupData)) {
        for (let i = attrGroupData.length - 1; i >= 0; i--) {
            let group = attrGroupData[i]
            // 检查当前属性组是否已经存在于当前型号的productAttrGroupList中
            if (existingGroupIds.includes(group.id)) {
                // 如果group.id已经存在，则跳过
                continue;
            }
            currentTab.productAttrGroupList.push({
                groupId: group.id,
                groupName: group.groupName,
                productAttrs: group.attrClassifyList.map((item: any) => ({
                    attrId: item.id,
                    attrName: item.className
                }))
            });
        }
        ElMessage.success("属性组添加成功");
    } else {
        // 检查当前属性组是否已经存在于当前型号的productAttrGroupList中
        if (existingGroupIds.includes(attrGroupData.id)) {
            // 如果group.id已经存在，则跳过
            ElMessage.success("属性组已添加");
            return;
        }
        currentTab.productAttrGroupList.push({
            groupId: attrGroupData.id,
            groupName: attrGroupData.groupName,
            productAttrs: attrGroupData.attrClassifyList.map((item: any) => ({
                attrId: item.id,
                attrName: item.className
            }))
        });
        ElMessage.success("属性组添加成功");
    }
};

/**
 * 同步属性组功能
 * 将第一个型号的属性组同步到当前型号
 * @param currentItem 当前型号对象
 * @param currentIndex 当前型号索引
 */
const syncAttributeGroups = (currentItem: Product, currentIndex: number) => {
    // 检查是否有型号数据
    if (!editableTabs.value || editableTabs.value.length === 0) {
        ElMessage.warning('没有可同步的型号数据');
        return;
    }

    // 检查是否为第一个型号
    if (currentIndex === 0) {
        ElMessage.warning('第一个型号无法同步属性组');
        return;
    }

    // 获取第一个型号的属性组数据
    const firstProduct = editableTabs.value[0];
    if (!firstProduct.productAttrGroupList || firstProduct.productAttrGroupList.length === 0) {
        ElMessage.warning('第一个型号没有属性组数据可同步');
        return;
    }

    // 检查当前型号是否已有属性组且有ID（表示已保存）
    const hasExistingGroups = currentItem.productAttrGroupList?.some(group => group.id);
    if (hasExistingGroups) {
        ElMessage.warning('当前型号已有保存的属性组，无法同步');
        return;
    }

    // 深拷贝第一个型号的属性组数据
    const syncedGroups = JSON.parse(JSON.stringify(firstProduct.productAttrGroupList));

    // 清除ID相关字段，因为这是新的属性组
    syncedGroups.forEach((group: any) => {
        delete group.id;
        delete group.productId;
        group.productAttrs?.forEach((attr: any) => {
            delete attr.id;
            delete attr.productId;
            delete attr.productAttrGroupId;
        });
    });

    // 将同步的属性组数据赋值给当前型号
    currentItem.productAttrGroupList = syncedGroups;

    ElMessage.success('属性组同步成功');
};

/**
 * 判断同步属性组按钮是否应该禁用
 * @param currentItem 当前型号对象
 * @param currentIndex 当前型号索引
 * @returns 是否禁用按钮
 */
const isSyncButtonDisabled = (currentItem: Product, currentIndex: number) => {
    // 如果是第一个型号，禁用按钮
    if (currentIndex === 0) {
        return true;
    }

    // 如果当前型号的属性组中有任何一个属性组有ID（表示已保存），禁用按钮
    const hasExistingGroups = currentItem.productAttrGroupList?.some(group => group.id);
    if (hasExistingGroups) {
        return true;
    }

    // 检查第一个型号是否有属性组数据
    if (!editableTabs.value || editableTabs.value.length === 0) {
        return true;
    }

    const firstProduct = editableTabs.value[0];
    if (!firstProduct.productAttrGroupList || firstProduct.productAttrGroupList.length === 0) {
        return true;
    }

    return false;
}

// 处理分类选择变化
const handleClassChange = (value: string[]) => {
    // 重置分类数据
    dataForm.class1Id = '';
    dataForm.class2Id = '';
    dataForm.class3Id = '';
    dataForm.className = '';

    if (!value || value.length === 0) return;

    // 递归查找分类选项
    const findClassById = (options: any[], id: string): any => {
        for (const option of options) {
            if (option.id === id) return option;
            if (option.children && option.children.length > 0) {
                const found = findClassById(option.children, id);
                if (found) return found;
            }
        }
        return null;
    };

    // 构建分类路径
    const classNames: string[] = [];

    // 设置一级分类
    dataForm.class1Id = value[0];
    const class1 = findClassById(classOptions.value, value[0]);
    if (class1) classNames.push(class1.className);

    // 设置二级分类
    if (value.length > 1) {
        dataForm.class2Id = value[1];
        const class2 = findClassById(classOptions.value, value[1]);
        if (class2) classNames.push(class2.className);
    }

    // 设置三级分类
    if (value.length > 2) {
        dataForm.class3Id = value[2];
        const class3 = findClassById(classOptions.value, value[2]);
        if (class3) classNames.push(class3.className);
    }

    // 合并分类名称
    dataForm.className = classNames.join('/');
    console.log('分类:', dataForm.className);
};

// 获取分类列表
const getClassList = () => {
    baseService.get('/noc/nocclassify/list2').then(res => {
        // 确保数据结构符合级联选择器要求
        classOptions.value = res.data;
        console.log('分类数据加载成功:', classOptions.value);
    }).catch(error => {
        console.error('获取分类数据出错:', error);
        ElMessage.error('获取分类数据出错');
    });
};

// 获取品牌列表
const getBrandList = (brandName: string) => {
    if  (!brandName) {
      return;
    }
    baseService.get('/base/basebrand/list1', {
        page: 1,
        limit: 5000,
        brandName: brandName
    }).then(res => {
        if (res && res.data) {
            brandOptions.value = res.data.list;
        }
    });
};

const cancel = () => {
    router.push('/program/nocproduct-list');
    // 关闭当前标签页（需确保useView hook已正确配置）
    state.closeCurrentTab();
};
// 页面进入执行
init();
// 加载分类和品牌数据
onMounted(() => {
    getClassList();
    // getBrandList();
});
</script>

<style lang="scss" scoped>
.el-input {
    width: 224px;
    height: 32px;
    opacity: 1;
    border-radius: 5px;
    background: rgba(255, 255, 255, 1);
}

.el-select {
    width: 224px;
    height: 32px;
    opacity: 1;
    border-radius: 5px;
    background: rgba(255, 255, 255, 1);
}

.form {
    display: flex;
    justify-content: space-between;
}

.image-upload-container {
    width: 511px;
    border: 1px dashed #ccc;
    border-radius: 6px;
    padding: 10px;
}

.upload-tip {
    font-size: 13px;
    color: rgba(168, 171, 178, 1);
    margin-bottom: 10px;
}

.tip-text {
    color: #999;
    font-size: 14px;
}

.upload-dragger {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}


.upload-over-tip {
    color: #999;
    text-align: center;
}

.quxiao {
    border-radius: 5px;
    background: rgba(239, 244, 255, 1);
    color: rgba(22, 119, 255, 1);
    border: 1px solid rgba(22, 119, 255, 1);
}

.foot {
    display: flex;
    justify-content: end;
    position: absolute;
    bottom: 50px;
    right: 50px;
}

.add-button {
    width: 100px;
    height: 32px;
    padding: 10px 20px;
    background-color: rgba(22, 119, 255, 1);
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    margin-bottom: 20px;
}

.add-button:hover {
    background-color: rgba(22, 119, 255, 1);
}

.model-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    justify-content: center;
}

.model-item {
    display: flex;
    align-items: center;
}

.model-select {
    padding: 8px;
    margin-right: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
}

.model-input {
    padding: 8px;
    margin-right: 10px;
    border-radius: 5px;
    width: 156px;
    height: 32px;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(199, 199, 199, 1);
}

.model-input:focus {
    border: 0px;
    /* 获得焦点时边框颜色改为蓝色 */
    background: rgba(240, 245, 255, 1);
    color: rgba(22, 119, 255, 1);
    outline: none;
    /* 去除默认的焦点轮廓 */
}

.remove-button {
    padding: 8px 12px;
    background-color: #f44336;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.uploaded-image {
    width: 100px;
    height: 100px;
    object-fit: cover;
}

.brand-upload {
    display: block;
}

.upload-box {
    width: 100px;
    height: 100px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: border-color 0.3s;
}

.upload-box:hover {
    border-color: #409EFF;
}

.upload-box .icon {
    width: 32px;
    height: 32px;
}

.upload-box .uploaded-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

// 产品图片/视频
.image-upload-section {
    display: flex;
    margin-bottom: 20px;
}

.image-upload-label {
    width: 50px;
}

.video-upload-section {
    display: flex;
}

.video-upload-label {
    width: 50px;
}

:deep(.el-upload--picture-card) {
    // background-repeat: no-repeat;
    // background-image: url(../../assets/images/upload.png);
    width: 80px !important;
    height: 80px !important;
}

.attribute-group {
    width: 684px;
    height: 100%;
    padding: 20px;
    border: 1px dashed rgba(31, 31, 31, 0.36);
    border-radius: 18px;
    margin-bottom: 38px;

}

.attribute-group-input {
    width: 492px;
    height: 32px;
}

:deep(.hide .el-upload--picture-card) {
    display: none;
}
:deep.el-upload-list--picture-card .el-upload-list__item {
    width: 300px;
}
.reject{
    margin-top: 20px;
    margin-left: 60px;
    height: 92px;
    border-radius: 6px;
    background-color: rgba(255,255,255,1);
    border: 1px solid rgba(187,187,187,1);
}
.reject span{
    font-weight: 600;
    margin-left: 30px;
    line-height: 92px;
    font-size: 16px;
}

</style>
